package com.example.student.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.student.entity.SysRole;
import com.example.student.entity.SysUser;
import com.example.student.mapper.SysMenuMapper;
import com.example.student.mapper.SysRoleMapper;
import com.example.student.mapper.SysUserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义UserDetailsService实现
 * 用于加载用户信息和权限
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper userMapper;
    
    @Resource
    private SysMenuMapper menuMapper;
    
    @Resource
    private SysRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        SysUser user = userMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
                        .eq(SysUser::getStatus, 1) // 只查询启用状态的用户
                        .eq(SysUser::getDeleted, 0) // 未删除的用户
        );
        
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在或已被禁用");
        }
        
        // 加载用户权限
        return createUserDetails(user);
    }
    
    /**
     * 创建UserDetails对象
     */
    private UserDetails createUserDetails(SysUser user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        // 获取用户角色列表
        List<SysRole> roles = roleMapper.selectRolesByUserId(user.getId());
        
        // 检查是否为管理员
        boolean isAdmin = roles.stream()
                .anyMatch(role -> "ROLE_ADMIN".equals(role.getRoleCode()));
        
        // 将角色添加到权限列表
        authorities.addAll(roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getRoleCode()))
                .collect(Collectors.toList()));
        
        // 获取用户权限列表
        List<String> permissions;
        if (isAdmin) {
            // 管理员拥有所有权限
            permissions = menuMapper.selectAllPermissions();
        } else {
            // 普通用户根据角色获取权限
            permissions = menuMapper.selectPermissionsByUserId(user.getId());
        }
        
        // 将权限添加到权限列表
        authorities.addAll(permissions.stream()
                .filter(permission -> permission != null && !permission.isEmpty())
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList()));
        
        // 将权限列表设置到用户对象
        user.setAuthorities(authorities);
        
        // 设置角色列表（用于前端展示）
        List<String> roleList = roles.stream()
                .map(SysRole::getRoleName)
                .collect(Collectors.toList());
        user.setRoleList(roleList);
        
        return user;
    }
} 